<!DOCTYPE html>
<html>
<meta charset="UTF-8">
<head>
  <title>一伴实时渲染</title>
  <style>
    table {
      border-collapse: collapse;
    }

    th, td {
      padding: 8px;
      border: 1px solid black;
    }

    .avatar {
      width: 100px;
      height: 100px;
    }
  </style>
</head>
<body>
<table id="message-table">
  <thead>
  <tr>
    <th>头像</th>
    <th>描述</th>
    <th>时间</th>
  </tr>
  </thead>
  <tbody></tbody>
</table>

<script>
  function renderMessage(message) {
    const messageTable = document.getElementById('message-table');
    const tbody = messageTable.getElementsByTagName('tbody')[0];

    // 创建新行
    const newRow = document.createElement('tr');

    // 创建 avatar 列
    const avatarCell = document.createElement('td');
    const avatarElement = document.createElement('img');
    avatarElement.classList.add('avatar');
    avatarElement.src = message.avatar_url;
    avatarCell.appendChild(avatarElement);
    newRow.appendChild(avatarCell);

    // 创建 viewStr 列
    const viewStrCell = document.createElement('td');
    viewStrCell.textContent = message.viewStr;
    newRow.appendChild(viewStrCell);

    // 创建时间列
    const timeCell = document.createElement('td');
    const now=new Date();
    let hour = now.getHours(); // 小时，0-23
    hour=(hour-12)>0?hour-12:hour;
    const minute = now.getMinutes(); // 分钟，0-59
    const second = now.getSeconds(); // 秒数，0-59
    const currentTime = hour+"点"+minute+"分"+second;
    timeCell.textContent = currentTime;
    newRow.appendChild(timeCell);
    tbody.appendChild(newRow);
  }

  // 创建 WebSocket 连接
  const socketUrl = 'ws://127.0.0.1:1030/websocket/yiban';
  let socket;

  function connectWebSocket() {
    // 创建 WebSocket 连接
    socket = new WebSocket(socketUrl);

    // 监听连接成功事件
    socket.onopen = function(event) {
      console.log('WebSocket 连接成功');
    };

    // 监听接收消息事件
    socket.onmessage = function(event) {
      const message = JSON.parse(event.data);
      console.log('接收到消息:', message);

      // 将消息渲染到表格中
      renderMessage(message);
      window.scrollTo(0, document.body.scrollHeight);
    };

    // 监听连接关闭事件
    socket.onclose = function(event) {
      console.log('WebSocket 连接关闭');
      // 重新连接
      retryConnectWebSocket();
    };

    // 监听连接错误事件
    socket.onerror = function(error) {
      console.error('WebSocket 错误:', error);
      // 重新连接
      retryConnectWebSocket();
    };
  }

  function retryConnectWebSocket() {
    console.log('尝试重新连接...');
    // 断开连接
    socket = null;
    // 3秒后重新连接
    setTimeout(connectWebSocket, 3000);
  }

  // 初始连接
  connectWebSocket();

</script>
</body>
</html>